package Communicate;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author wuhan
 * @date 2019/9/19 15:22
 */

class Producer implements Runnable{
    private Resource res;
    Producer(Resource res){
        this.res=res;
    }

    @Override
    public void run() {
        while (true){
            try {
                res.set("Goods");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class Consumer implements Runnable{
    private Resource res;
    Consumer(Resource res){
        this.res=res;
    }

    @Override
    public void run() {
        while (true){
            try {
                res.out();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}


class Resource{

    private Lock lock=new ReentrantLock();
    private Condition conditionCon =  lock.newCondition();
    private Condition conditionPro =  lock.newCondition();


    private String name;
    private int count=1;
    private boolean flag=false;
    public  void set(String name) throws InterruptedException {
        lock.lock();
        try {
            while (flag){
                conditionPro.await();
            }
            this.name=name+"--"+count++;
            System.out.println(Thread.currentThread().getName()+"生产者---"+this.name);
            flag=true;
            conditionCon.signalAll();
        }
        finally {
            lock.unlock();
        }

    }
    public  void out() throws InterruptedException {
        lock.lock();
        try {
            while (!flag) {
                conditionCon.await();
            }
            System.out.println(Thread.currentThread().getName()+"---消费者---"+this.name);
            flag=false;
            conditionPro.signalAll();
        }finally {
            lock.unlock();
        }
    }
}
public class ProduceConsumer {
    public static void main(String[] args) {
        Resource resource =new Resource();
        Producer producer=new Producer(resource);
        Consumer consumer=new Consumer(resource);
        Thread t1=new Thread(producer);
        Thread t3=new Thread(producer);
        Thread t4=new Thread(consumer);
        Thread t2=new Thread(consumer);
        t1.start();t3.start();
        t2.start();t4.start();
    }
}